import { useRef, useState } from 'react'
import { DeleteFilled } from '@ant-design/icons'
import { Button, Modal, Select } from 'antd'
import { createScopeDetailItem, editScopeDetailItem, getParkList } from '@/api/shoppingCart.ts'
import { message } from '@hs-admin/utils'
import { commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'

const useEditParkScope = () => {
  const parentId = useRef('')
  const selfId = useRef('')
  const callFun = useRef(() => {
    console.log('do nothing')
  })
  const [open, setOpen] = useState(false)

  const [parkOptions, setParkOptions] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const searchPark = (word?: string) => {
    getParkList({
      keyword: word
    }).then((res) => {
      setParkOptions(
        (res.items ?? []).map((item: any) => ({
          label: item.park_name,
          value: item.id
        }))
      )
    })
  }

  const [isChoosing, setIsChoosing] = useState(false)

  const [parkList, setParkList] = useState<
    Array<{
      name: string
      value: string
    }>
  >([])

  const [parkValue, setParkValue] = useState<null | {
    label: string
    value: string
  }>(null)

  return {
    EditParkScope: (
      <Modal
        open={open}
        title="园区范围选择"
        onOk={async () => {
          if (selfId.current) {
            await editScopeDetailItem(selfId.current, {
              values: parkList
            })
          } else {
            await createScopeDetailItem({
              type: 'park',
              sub_scope_id: parentId.current,
              values: parkList
            })
          }
          setOpen(false)
          callFun.current()
        }}
        onCancel={() => {
          setOpen(false)
        }}>
        <div className="flex flex-col gap-4 max-h-70vh">
          <>
            {parkList.map((park) => (
              <div key={park.value} className="grid grid-cols-24">
                <div className="col-span-23 grid grid-cols-24 gap-1">
                  <span className="col-span-24 font-900">{park.name}</span>
                  <span className="col-span-20"> ID:{park.value}</span>
                </div>
                <DeleteFilled
                  className="justify-self-end"
                  onClick={() => {
                    setParkList((prevState) => prevState.filter((it) => it.value !== park.value))
                  }}
                />
              </div>
            ))}
            {isChoosing ? (
              <div className="flex gap-4">
                <Select
                  className="flex-1"
                  showSearch
                  {...commonSelectProps}
                  onSearch={searchPark}
                  onFocus={() => searchPark()}
                  value={parkValue?.value}
                  onChange={(_, option) => {
                    setParkValue(option)
                  }}
                  options={parkOptions}></Select>
                <Button
                  type="primary"
                  onClick={() => {
                    if (parkValue) {
                      if (parkList.some((item) => item.value === parkValue.value)) {
                        message.error('已存在')
                        return
                      }
                      setParkList((prevState) => [
                        ...prevState,
                        {
                          name: parkValue.label,
                          value: parkValue.value
                        }
                      ])
                      setParkValue(null)
                      setIsChoosing(false)
                    }
                  }}>
                  确定
                </Button>
                <Button
                  onClick={() => {
                    setIsChoosing(false)
                  }}>
                  取消
                </Button>
              </div>
            ) : (
              <Button type="primary" onClick={() => setIsChoosing(true)}>
                + 添加园区
              </Button>
            )}
          </>
        </div>
      </Modal>
    ),
    openModal: (
      parent: string,
      self: string,
      oldValues: Array<{
        name: string
        value: string
      }>,
      call: () => void
    ) => {
      console.log('建立')
      setParkValue(null)
      setIsChoosing(false)
      parentId.current = parent
      selfId.current = self
      callFun.current = call
      setParkList(oldValues)
      setOpen(true)
    }
  }
}

export default useEditParkScope
